package config

import (
	"github.com/spf13/viper"
	"go.uber.org/zap"
	"go.uber.org/zap/zapcore"
	"suitbim.com/media/utils"
)

var g GlobalConfig

func GetGlobal() *GlobalConfig {
	return &g
}

func Load(config any, filePath string) {
	//v := viper.New()
	viper.SetConfigFile(filePath)
	handError(viper.ReadInConfig())
	handError(viper.Unmarshal(config))
}

func handError(err error) {
	if err != nil {
		panic(err)
	}
}

type application struct {
	Mode string
	Log  struct {
		File  string
		Level string
	}
	DBPath string
}

type SHP struct {
	Schema string
	Host   string
	Port   int
}

type dispatcher struct {
	Capture struct {
		Schema string
		Port   int
	}
	Stream struct {
		Schema string
		Host   string
		Port   int
	}
	Signal struct {
		Schema string
		Host   string
		Port   int
	}
	Viewer struct {
		Schema string
		Host   string
		Port   int
	}
	Business struct {
		Schema string
		Host   string
		Port   int
	}
}

type GlobalConfig struct {
	// 应用程序实例
	App application
	// 日志实例
	Log *zap.SugaredLogger
	// 远端流分发服务器相关配置实例
	Dispatcher dispatcher
	// 临时路径
	TempPath string
}

func (g *GlobalConfig) String() string {
	return utils.Struct2JsonString(g)
}

// Init 初始化配置文件解析
func init() {
	// 加载配置文件
	Load(&g, "./config.yml")
	// 设置日志级别
	var level zapcore.Level
	switch g.App.Log.Level {
	case "debug":
		level = zapcore.DebugLevel
	case "info":
		level = zapcore.InfoLevel
	case "warn":
		level = zap.WarnLevel
	case "error":
		level = zapcore.ErrorLevel
	case "fatal":
		level = zapcore.FatalLevel
	default:
		level = zapcore.InfoLevel
	}
	// 初始化日志器
	g.Log = utils.InitLogger(level,
		g.App.Log.File,
		g.App.Mode == "dev")
	// 全局配置初始化完成
	g.Log.Infof("\n%s", GetBannerString())
	g.Log.Info("==== Global configuration initialled ====")
	// g.Log.Debugf("==== Global configuration value:\n%s\n", g.String())
}
